package com.example.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.example.now.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Client extends Activity implements OnClickListener {

	final static int CONNECT_FAIL = 1;
	final static int SHUTDOWN = 2;

	private Handler mHandler;

	private Button button1, button2, button3;
	private String host;
	private final static int port = 5432;
	private static String filename = "config.txt";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		button1 = (Button) findViewById(R.id.button1);
		button2 = (Button) findViewById(R.id.button2);
		button3 = (Button) findViewById(R.id.button3);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);

		mHandler = new MyHandler();

		FileInputStream fis = null;
		try {
			fis = openFileInput(filename);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			host = br.readLine();
			br.close();
			fis.close();
		} catch (FileNotFoundException e) {
			host = "172.18.63.44";
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onClick(View v) {
		if (v == button1) {
			shutdown();
		} else if (v == button2) {
			Intent newIntent = new Intent();
			Bundle myBund = new Bundle();
			myBund.putString("host", host);
			myBund.putInt("port", port);
			newIntent.putExtras(myBund);
			newIntent.setClass(Client.this, CMD.class);
			startActivityForResult(newIntent, 0);
		} else if (v == button3) {
			setIP();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			Bundle bunde = data.getExtras();
			host = bunde.getString("host");
			break;
		default:
			break;
		}
	}

	private void shutdown() {
		new AlertDialog.Builder(this)
				.setMessage("Shut down the computer?")
				.setPositiveButton("Sure",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
								String message = sendCommand("shutdown -s",
										connect());
								if (message != null) {
									sendMessage(SHUTDOWN);
								}
							}
						}).setNegativeButton("Cancel", null).show();
	}

	private void setIP(){
		final EditText editText = new EditText(this);
		editText.setText(host);
		editText.setMaxEms(15);
		editText.setGravity(Gravity.RIGHT);
		editText.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
		new AlertDialog.Builder(this)
			.setTitle("Input IP address")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView(editText)
			.setPositiveButton("Sure",
				new DialogInterface.OnClickListener() {
					public void onClick(
							DialogInterface dialoginterface, int i) {
						FileOutputStream fos = null;
						host = editText.getText().toString();
						try {
							fos = openFileOutput(filename, Context.MODE_PRIVATE);
							BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
							bw.write(host + "\n");
							bw.flush();
							bw.close();
							fos.close();
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}					
			}).setNegativeButton("Cancle", null)
			.show();
	}

	private Socket connect() {
		Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(InetAddress.getByName(host),
					port), 3000);
		} catch (Exception e) {
			sendMessage(CONNECT_FAIL);
		}
		return socket;
	}

	private String sendCommand(String command, Socket socket) {
		if (socket.isConnected()) {
			try {
				PrintStream ps = new PrintStream(socket.getOutputStream());
				ps.print(command + "\n");
				ps.flush();
				return "The computer is shutting down..";
			} catch (IOException e) {
				return null;
			}
		}
		return null;
	}

	private void sendMessage(int what) {
		Message message = new Message();
		message.what = what;
		mHandler.sendMessage(message);
	}

	private class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case CONNECT_FAIL:
				new AlertDialog.Builder(Client.this)
						.setMessage("Connection Failed")
						.setPositiveButton("Sure", null).show();
				break;
			case SHUTDOWN:
				new AlertDialog.Builder(Client.this)
						.setMessage("Shutting down.")
						.setPositiveButton("Sure", null).show();
				break;
			default:
				break;
			}
		}
	}
}
